import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterxc/pages/search_paeg.dart';
import 'package:flutterxc/plugin/asr_manager.dart';

class SpeakPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SpeakPageState();
}

class _SpeakPageState extends State<SpeakPage>
    with SingleTickerProviderStateMixin {
  String _spackTip = '按下说话';
  Animation<double> animation;
  AnimationController _animationController;
  String _spackRes = '';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 1));
    animation =
    CurvedAnimation(parent: _animationController, curve: Curves.easeIn)
      ..addStatusListener((AnimationStatus status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        } else if (status == AnimationStatus.dismissed) {
          _animationController.forward();
        }
      });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(30),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _topItem(),
              _bottomButton()
            ],
          ),
        ),
      ),
    );
  }

  _topItem() {
    return Container(
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
            child: Text(
              '你可以这样说', style: TextStyle(color: Colors.black87, fontSize: 16),),
          ),
          Text('故宫门票\n北京一日游\n迪士尼乐园',
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey, fontSize: 14),),
          Padding(
            padding: EdgeInsets.all(20),
            child: Text(_spackRes,style: TextStyle(color: Colors.blue),),
          )
        ],
      ),
    );
  }

  _bottomButton() {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Stack(
        children: <Widget>[
          GestureDetector(
            onTapDown: (e) {
              _speckStart();
            },
            onTapUp: (e) {
              _spackEnd();
            },
            onTapCancel: () {},
            child: Center(
              child: Column(
                children: <Widget>[
                  Padding(
                      padding: EdgeInsets.all(10),
                      child: Text(
                        _spackTip,
                        style: TextStyle(color: Colors.blue, fontSize: 12),
                      )),
                  Stack(
                    children: <Widget>[
//                      防止动画导致 盒子大小变化时 造成 布局的变化，外层套上一个固定 盒子
                      Container(
                        height: MIC_SIZE,
                        width: MIC_SIZE,
                      ),
                      Center(
                        child: AnimatedMic(
                          animation: animation,
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
          ),
          Positioned(
            right: 10,
            bottom: 20,
            child: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Icon(Icons.close, size: 30, color: Colors.grey,),
            ),
          )
        ],
      ),
    );
  }

  _speckStart() {
    _animationController.forward();
    setState(() {
      _spackTip ='-- 识别中 --';
    });
    AsrManager.start().then((val){
      if (val != null && val.length != 0) {
        val = val.toString();
        if (val.endsWith(',') || val.endsWith('，')){
        print(val.endsWith(',') || val.endsWith('，'));
          val = val.substring(0,val.length - 1);
        }
        setState(() {
          _spackRes = val;
        });

        Navigator.pop(context);
        Navigator.push(context, MaterialPageRoute(builder: (context) => SearchPage(keyword: val,)));
        print('----- $val -----');
      }
    }).catchError((onError){
      print('语音识别失败' + onError);
    });
  }

  _spackEnd() {
    setState(() {
      _spackTip = '长按说话';
    });
    _animationController.reset();
    _animationController.stop();
    AsrManager.stop();
  }
}

const double MIC_SIZE = 80;

class AnimatedMic extends AnimatedWidget {
  static final _opacityTween = Tween<double>(begin: 1, end: 0.5);
  static final _sizeTween = Tween<double>(begin: MIC_SIZE, end: MIC_SIZE - 20);

  AnimatedMic({Key key, Animation<double> animation})
      : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    // TODO: implement build
    return Opacity(
      opacity: _opacityTween.evaluate(animation),
      child: Container(
        height: _sizeTween.evaluate(animation),
        width: _sizeTween.evaluate(animation),
        decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.circular(MIC_SIZE / 2)),
        child: Icon(
          Icons.mic,
          color: Colors.white,
          size: 30,
        ),
      ),
    );
  }
}
